package org.epidroid.epidroid.androsoul.engine.utils;

import org.epidroid.epidroid.R;
import org.epidroid.epidroid.androsoul.engine.AndroSoul;
import org.epidroid.epidroid.androsoul.engine.conversation.MessageItem;
import org.epidroid.epidroid.androsoul.engine.service.AndroSoulService;
import org.epidroid.epidroid.androsoul.engine.service.IAndroSoulServiceListener;
import org.epidroid.epidroid.androsoul.ui.conversation.ConversationActivity;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Message;
import android.os.Vibrator;
import android.util.Log;

public class AndroSoulNotificationsListener implements
		IAndroSoulServiceListener {

	private boolean _notificationsEnabled = true;
	private NotificationManager _NM = null;
	private AndroSoulService _service = null;
	private boolean _notifContactLogin = true;
	private boolean _notifContactLogoff = true;
	private boolean _notifMessageReceived = true;

	public AndroSoulNotificationsListener(NotificationManager NM,
			AndroSoulService c) {
		_NM = NM;
		_service = c;
	}

	public void enableNotifs(boolean enable) {
		_notificationsEnabled = enable;
	}

	@Override
	public void dataChanged(Message o) {
		switch (o.what) {
		case AndroSoul.RECEIVE_MESSAGE:
			receivedMessage(o);
			break;
		case AndroSoul.WIZZ:
			Vibrator vib = (Vibrator) _service
					.getSystemService(Context.VIBRATOR_SERVICE);
			vib.vibrate(500);
			break;
		case AndroSoul.EXT_USER_LOG:
			if (o.arg1 == 2)
				_service.showServiceRunningNotification(true);
			break;
		case AndroSoul.DECONNECTED:
			_service.showServiceRunningNotification(false);
			break;
		default:
			break;
		}
	}

	private void receivedMessage(Message msg) {
		if (!_notificationsEnabled || !_notifMessageReceived)
			return;

		MessageItem message = (MessageItem) msg.obj;
		Notification notification = new Notification(R.drawable.androsoul,
				message.getAuthor() + ": " + message.getContent(),
				System.currentTimeMillis());
		notification.flags |= (Notification.FLAG_AUTO_CANCEL
				| Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE);
		long[] vibrate = { 0, 100, 200, 300 };
		notification.vibrate = vibrate;
		Intent i = new Intent(_service, ConversationActivity.class);
		i.putExtra("contact", message.getAuthor());
		Log.v(AndroSoul.LOGCAT, message.getAuthor() + "!");
		PendingIntent contentIntent = PendingIntent.getActivity(_service, 0, i,
				PendingIntent.FLAG_UPDATE_CURRENT);
		notification.setLatestEventInfo(_service, message.getAuthor(),
				message.getContent(), contentIntent);
		_NM.notify(msg.arg1, notification);
	}

	public void enableNotifContactLogin(boolean value) {
		_notifContactLogin = value;
	}

	public void enableNotifContactLogoff(boolean value) {
		_notifContactLogoff = value;
	}

	public void enableNotifMessageReceived(boolean value) {
		_notifMessageReceived = value;
	}

}
